const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const conn = require('../../db/mysql');
const svgCaptcha = require('svg-captcha');
const imageCodeConfig = require('../../utils/imageCode');
const { jwtCheck } = require('../../utils/jwt');
// 初始化使用下面这个conn，建数据库
// const conn = require('../../db/init/index');
const sha256 = require('../../utils/sha256');
const { secretKey } = require('../../utils/constant');
const { redisSet, redisGet } = require('../../utils/redisConfig.js');
conn.getConnection((err, conn) => {
    if (err) {
        console.log("连接失败,失败信息为：" + err);
    }
})
/**
 * 获取登录验证码
 * @summary 获取登录验证码
 * @route GET /imageCode
 * @group 用户登录
 * @returns {object} 200 - {code: 200,msg: "获取成功",type: "success",data: {imageDate:dtring,imageCode:string}}
 * @returns {Error}  default - {code:500,msg: "获取成功",type: "fail",data:{ }}
 */
router.get('/imageCode', (req, res) => {
    let imageCode = svgCaptcha.create(imageCodeConfig);
    let dataTemplent = {
        code: 200,
        msg: "获取成功",
        type: "success",
        data: {
            imageData: imageCode.data,
            codeKey: imageCode.text.split('')[1] + Date.now() + imageCode.text.split('')[2]
        }
    }
    // console.log(typeof imageCode.text)
    redisSet(dataTemplent.data.codeKey, imageCode.text, 60).then(() => {

    })
    redisGet(dataTemplent.data.codeKey).then((val) => {
        // console.log(val);
    })
    res.send(dataTemplent);
});
/**
 * 用户登录
 * @summary 用户登录
 * @route POST /login
 * @group 用户登录
 * @param {string} userInfo.body.required - account、password、keycode、value
 * @returns {object} 200 - {code: 200,msg: "登录成功",type: "success",data:{token:""}}
 * @returns {Error}  default - {code:400,msg:'登录失败',type="fail",data:{ }}
 */
router.post('/login', (req, res, next) => {
    let params = req.body;
    let dataTemplent = {
        code: 200,
        msg: "登录成功",
        type: "success",
        data: {
            token: ""
        }
    }
    if (params) {
        redisGet(params.keyCode).then((val) => {
            if (!val) {
                dataTemplent.code = 400;
                dataTemplent.type = "fail";
                dataTemplent.msg = "验证码已过期";
                res.send(dataTemplent);
            } else if (params.value.toLowerCase() !== val.toLowerCase()) {
                dataTemplent.code = 400;
                dataTemplent.type = "fail";
                dataTemplent.msg = "验证码错误";
                res.send(dataTemplent);
            } else {
                const password = sha256(params.password);
                const sql = `select * from user where account='${params.account}' and password='${password}' LIMIT 1`;
                conn.query(sql, (err, result) => {
                    if (err || !result.length) {
                        dataTemplent.code = 400;
                        dataTemplent.type = "fail";
                        dataTemplent.msg = "用户名或密码错误";
                        res.send(dataTemplent);
                    } else {
                        // console.log(result)
                        dataTemplent.code = 200;
                        dataTemplent.type = "success";
                        dataTemplent.msg = "登录成功";
                        let tokenObj = { account: result[0].user_id };
                        let token = jwt.sign(tokenObj, secretKey, {
                            expiresIn: 60 * 60 * 24 // 授权时效24小时
                        });
                        dataTemplent.result = result;
                        dataTemplent.data.token = token;
                        res.send(dataTemplent);
                    }
                });
            }
        })
    }
});
/**
 * 重置密码
 * @summary 重置密码
 * @route POST /resetPassword
 * @group 重置密码
 * @param {string} info.body.required - newPassword、oldPassword
 * @returns {object} 200 - {code: 200,msg: "登录成功",type: "success",data:{}}
 * @returns {Error}  default - {code:400,msg:'登录失败',type="fail",data:{ }}
 */
router.post('/resetPassword', (req, res, next) => {
    let params = req.body;
    let token = jwtCheck(req.headers.authorization) || {};
    let dataTemplent = {
        code: 200,
        msg: "修改成功",
        type: "success",
        data: {}
    }
    if (params.newPassword && params.oldPassword) {
        let password = sha256(params.oldPassword);
        let id=token.msg.account ||0;
        let sql = `select * from user where user_id='${id}' and password='${password}' LIMIT 1`;
        conn.query(sql, (err, result) => {
            if (err || !result.length) {
                dataTemplent.code = 400;
                dataTemplent.type = "fail";
                dataTemplent.msg = "原密码错误";
                res.send(dataTemplent);
            } else {
                password = sha256(params.newPassword);
                sql = `update user set password='${password}' where user_id=${id}`;
                conn.query(sql, (err2, result2) => {
                    res.send(dataTemplent);
                })
            }
        })
    } else {
        dataTemplent.code = 400;
        dataTemplent.type = "fail";
        dataTemplent.msg = "修改失败";
        res.send(dataTemplent);
    }
});

module.exports = router;